import { useSearchParams, useNavigate } from "react-router-dom"
import { useState, useEffect } from "react";
import HCTitle from "@/components/hc-title"
import EditContent from "./components/EditContent"
import dayjs from 'dayjs';
import api from '@/api'
import { message } from "antd";
import { useDispatch, useSelector } from "react-redux";
import { closeCurrentTab } from '@/store/modules/tabListSlice';

const Edit = () => {
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const tabList = useSelector(state => state.tabList.tabList)

  const [form, setForm] = useState({});
  const [formOptions, setFormOptions] = useState({})
  const [fileList, setFileList] = useState([])

  const [searchParams] = useSearchParams()
  const id = searchParams.get("id")
  const projectId = searchParams.get('projectId')
  const isNew = id === null
  const title = isNew ? '新建任务' : `编辑任务ID${id}`
  const [initialValues, setInitialValues] = useState({
    start_on: dayjs(new Date()),
    finish_on: null,
    project_id: projectId ? +projectId : null,
    project_name: "xxxx"
  })

  const btnGroup = [
    { text: '保存', type: 'primary', action: 'handleSave' },
  ]

  const initProjectList = () => {
    api.dataset.getChildrenById({ id: 14 }).then((res) => {
      const projectList = res.data.map(item => ({ id: item.id, value: item.name }))
      setFormOptions(formOptions => ({
        ...formOptions,
        projectList
      }))
    })
  }

  const initLanguageList = () => {
    api.dataset.getChildrenById({ id: 20 }).then((res) => {
      const languageList = res.data.map(item => ({ id: item.id, value: item.name }))
      setFormOptions(formOptions => ({
        ...formOptions,
        languageList
      }))
    })
  }

  const initTypeList = () => {
    api.dataset.getChildrenById({ id: 16 }).then((res) => {
      const typeList = res.data.map(item => ({ id: item.id, value: item.name }))
      setFormOptions(formOptions => ({
        ...formOptions,
        typeList
      }))
    })
  }

  const initDetail = () => {
    api.board.getDetailById(id).then(res => {
      // TODO 不是实际的数据，需要替换
      const info = res.data
      info.start_on = info.start_on ? dayjs(info.start_on) : null
      info.finish_on = info.finish_on ? dayjs(info.finish_on) : null
      setInitialValues(info)
    })
  }

  const initFileList = () => {
    const param = {
      relateType: 'Pdca',
      relateId: id
    }
    api.file.getFileList(param).then(res => {
      setFileList(res.data)
    })
  }

  const handleSave = () => {
    const bForm = JSON.parse(JSON.stringify(form))
    bForm.mark = Number(bForm.mark)
    bForm.start_on = bForm.start_on ? dayjs(bForm.start_on).format("YYYY-MM-DD") : null
    bForm.finish_on = bForm.finish_on ? dayjs(bForm.finish_on).format("YYYY-MM-DD") : null
    bForm.project_name = !bForm.project_id ? '' : formOptions.projectList.find(item => item.id === bForm.project_id).value
    bForm.language_name = !bForm.language_id ? '' : formOptions.languageList.find(item => item.id === bForm.language_id).value
    bForm.type_name = !bForm.type_id ? '' : formOptions.typeList.find(item => item.id === bForm.type_id).value
    if (isNew) {
      api.board.add(bForm).then(async res => {
        if (fileList && fileList.length) {
          const { id } = res.data[0]
          const params = {
            id,
            fileList,
            type: 'Pdca'
          }
          await api.file.relate(params)
        }
        message.success('保存成功')
        const lastTab = tabList[tabList.length - 2]
        navigate(lastTab.path)
        dispatch(closeCurrentTab())
      })
    } else {
      bForm.id = id
      const updateForm = { ...initialValues, ...bForm }
      api.board.update(updateForm).then(res => {
        // 重复关联附件
        if (fileList && fileList.length) {
          const params = {
            id,
            fileList,
            type: 'Pdca'
          }
          api.file.relate(params).then(res => {
            message.success('保存成功')
            const lastTab = tabList[tabList.length - 2]
            navigate(lastTab.path)
            dispatch(closeCurrentTab())
          })
        } else {
          message.success('保存成功')
          const lastTab = tabList[tabList.length - 2]
          navigate(lastTab.path)
          dispatch(closeCurrentTab())
        }
      })
    }
  }
  
  useEffect(() => {
    initProjectList();
    initLanguageList();
    initTypeList();

    if (id) {
      initDetail()
      initFileList()
    }
  }, []);

  useEffect(() => {
    if (id) {
      initDetail()
      initFileList()
    }
  }, [id])

  return (
    <div>
      <HCTitle title={title} btnGroup={btnGroup} handleSave={handleSave}></HCTitle>
      <EditContent initialValues={initialValues} setForm={setForm} formOptions={formOptions} fileList={fileList} setFileList={setFileList} />
    </div>
  )
}

export default Edit
